package com.thinkgem.dingdan.modules.bu.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.thinkgem.dingdan.common.config.Global;
import com.thinkgem.dingdan.common.persistence.Page;
import com.thinkgem.dingdan.common.utils.IdGen;
import com.thinkgem.dingdan.common.utils.StringUtils;
import com.thinkgem.dingdan.common.utils.excel.ExportToExcelUtil;
import com.thinkgem.dingdan.common.web.BaseController;
import com.thinkgem.dingdan.modules.bu.constant.BusinessConstant;
import com.thinkgem.dingdan.modules.bu.entity.BuOrder;
import com.thinkgem.dingdan.modules.bu.entity.BuOrderCp;
import com.thinkgem.dingdan.modules.bu.entity.BuSalesman;
import com.thinkgem.dingdan.modules.bu.entity.TotalEntity;
import com.thinkgem.dingdan.modules.bu.service.BuOrderCpService;
import com.thinkgem.dingdan.modules.bu.service.BuOrderService;
import com.thinkgem.dingdan.modules.bu.service.BuSalesmanService;
import com.thinkgem.dingdan.modules.bu.service.IBuCustomerService;
import com.thinkgem.dingdan.modules.bu.service.IBuSupplierService;
import com.thinkgem.dingdan.modules.bu.utils.DateUtil;
import com.thinkgem.dingdan.modules.bu.utils.ExcelTest;
import com.thinkgem.dingdan.modules.bu.utils.OrderStateEnum;
import com.thinkgem.dingdan.modules.bu.wrapper.InternalReturnWrapper;
import com.thinkgem.dingdan.modules.bu.wrapper.ModelWrapper;
import com.thinkgem.dingdan.modules.cms.entity.Site;
import com.thinkgem.dingdan.modules.sys.entity.Office;
import com.thinkgem.dingdan.modules.sys.entity.Role;
import com.thinkgem.dingdan.modules.sys.entity.User;
import com.thinkgem.dingdan.modules.sys.service.IUserService;
import com.thinkgem.dingdan.modules.sys.utils.UserUtils;

/**
 * 内部订单Controller
 * 
 * @author ThinkGem
 * @version 2018-08-26
 */
@Controller
@RequestMapping(value = "${adminPath}/bu/buInternalOrder")
public class BuInternalOrderController extends BaseController {

	@Autowired
	private BuOrderService buOrderService;

	@Resource
	private IBuSupplierService buSupplierService;

	@Resource
	private IBuCustomerService buCustomerService;

	@Resource
	private BuOrderCpService buOrderCpService;

	@Resource
	private IUserService userService;
	
	@Resource
	private BuSalesmanService buSalesmanService;
	
	@Value("${win.userfiles.basedir}")
	private String winUserfilesBasedir;

	@Value("${linux.userfiles.basedir}")
	private String linuxUserfilesBasedir;
	
	@Value("${aliyunPicPrefixUrl}")
	private String picPrefix;

	@ModelAttribute
	public BuOrder get(@RequestParam(required = false) String id) {
		BuOrder entity = null;
		if (StringUtils.isNotBlank(id)) {
			BuOrder order = new BuOrder();
			order.setId(id);
			order.setDelFlag("0");
			entity = buOrderService.get(order);
		}
		if (entity == null) {
			entity = new BuOrder();
		}
		return entity;
	}

	/**
	 * flag (0:审核;1:修改;2:查看;3:新增;4:复制)
	 * @param buOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = { "list", "" })
	public String list(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {

		Page<BuOrder> page = null;
		try{
			if(StringUtils.isBlank(buOrder.getInnerSalVal())){
				buOrder.setSalesmanId("");
			}
			if(StringUtils.isBlank(buOrder.getInnerSupVal())){
				buOrder.setSupplierId("");
			}
			
			User user = UserUtils.getUser();
			List<String> roleList = user.getRoleIdList();
			String roleId = String.valueOf(roleList.get(0));
			buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
			buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
			if(org.apache.commons.lang3.StringUtils.isNotBlank(buOrder.getSalesmanId())){
				if(!buOrder.getSalesmanId().equals(BusinessConstant.SEL_ORDER_STATE_FLAG)){
					BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
					buOrder.setSalesManName(salesMan.getSalesmanName());
				}
			}
			InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
			
			if(roleId.equals(BusinessConstant.SUPPLIER_ROLE_ID_001) || roleId.equals(BusinessConstant.SUPPLIER_ROLE_ID_002)){
				returnWrapper = this.constructSupplier(user, buOrder);
			}else{
				returnWrapper = this.constructAdmin(buOrder, user);
			}
			if (StringUtils.isNoneBlank(buOrder.getOrderState())) {
				if (buOrder.getOrderState().equals(BusinessConstant.SEL_ORDER_STATE_FLAG)) {
					buOrder.setOrderState("");
				} else {
					buOrder.setOrderState(buOrder.getOrderState().split(",")[0]);
				}
			}
			
			String negativeOne = "-1";
			if(StringUtils.isBlank(buOrder.getOrderState()) || (negativeOne).equals(buOrder.getOrderState())){
				List<String> orderStateList = constructOrderState();
				buOrder.setOrderStateList(orderStateList);
			}
			if((BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSupplierId())){
				buOrder.setSupplierId("");
			}
			if((BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
				buOrder.setSalesmanId("");
			}
			page = buOrderService.findPage(new Page<BuOrder>(request, response), buOrder);
			Integer innerOrderState = -1;
			if(!org.apache.commons.lang3.StringUtils.isBlank(buOrder.getOrderState())){
				innerOrderState = Integer.parseInt(buOrder.getOrderState());
			}
		
			String innerSalVal = "-1";
			if(StringUtils.isNotBlank(buOrder.getSalesmanId())){
				innerSalVal = buOrder.getSalesmanId();
			}
			
			ModelWrapper modelWrapper = new ModelWrapper(page, returnWrapper, innerOrderState,innerSalVal);
			model = this.returnModel(model, modelWrapper);
			
		}catch(Exception e){
			e.printStackTrace();
			addMessage(redirectAttributes, "查询订单数据失败！失败信息："+e.getMessage());
		}
		return "modules/bu/buInternalOrderList";
	}
	
	private Model returnModel(Model model,ModelWrapper modelWrapper){
		
		model.addAttribute("picPrefix", picPrefix);
		model.addAttribute("page", modelWrapper.getPage());
		model.addAttribute("entity", modelWrapper.getReturnWrapper().getTotalEntity());
		model.addAttribute("innerOrderState",modelWrapper.getInnerOrderState());
		model.addAttribute("innerSupVal",modelWrapper.getReturnWrapper().getInnerVal());
		
		model.addAttribute("innerCusVal",modelWrapper.getReturnWrapper().getInnerVal());
		model.addAttribute("innerSalVal",modelWrapper.getInnerSalVal());
		model.addAttribute("supplierList",modelWrapper.getReturnWrapper().getSupplierList());
		
		return model;
		
	}

	private List<String> constructOrderState() {
		List<String> orderStateList = new ArrayList<>();
		orderStateList.add(String.valueOf(OrderStateEnum.C1000.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1001.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1002.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1003.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1004.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1005.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1006.getCode()));
		return orderStateList;
	}

	@RequiresPermissions("bu:buInternalOrder:operate:delivery")
	@RequestMapping(value = "selectById")
	public String selectById(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		String id = request.getParameter("id");
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		String orderState = request.getParameter("orderState");
		model.addAttribute("id", id);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		model.addAttribute("orderState", orderState);
		return "modules/bu/buInternalOrderDelivery";
	}
	
	@RequiresPermissions("bu:buInternalOrder:operate:toUpdate")
	@RequestMapping(value = "toUpdate")
	public String toUpdate(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag") == null ? "" : request.getParameter("flag");
		String write = request.getParameter("write");
		
		String customerId = buOrder.getCustomerId();
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(customerId);
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		
		model.addAttribute("entityList", entityList);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderEdit";

	}
	
	@RequiresPermissions("bu:buInternalOrder:operate:manageToUpdate")
	@RequestMapping(value = "manageToUpdate")
	public String manageToUpdate(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag") == null ? "" : request.getParameter("flag");
		String write = request.getParameter("write");
		
		String customerId = buOrder.getCustomerId();
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(customerId);
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		
		model.addAttribute("entityList", entityList);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderManageEdit";

	}
	
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag") == null ? "" : request.getParameter("flag");
		String write = request.getParameter("write");
		
		User user = UserUtils.getUser();
		buOrder.setCreateBy(user);
		String orderNo = DateUtil.getDate();
		buOrder.setOrderNo(orderNo);
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		buOrder.setOrderDate(format.format(new Date()));
		buOrder.setCreateUser(user.getName());
		
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(user.getId());
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		model.addAttribute("entityList", entityList);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderForm";

	}
	
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = "view")
	public String view(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {
		
		String flag = request.getParameter("flag") == null ? "": request.getParameter("flag");
		String write = request.getParameter("write");
		
		String salesManId = buOrder.getSalesmanId();
		BuSalesman salesMan = new BuSalesman();
		salesMan.setId(salesManId);
		salesMan.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		
		List<BuSalesman> entityList = new ArrayList<>();
		BuSalesman entity = buSalesmanService.get(salesMan);
		entityList.add(entity);
		
		model.addAttribute("entityList", entityList);
		model.addAttribute("buOrder", buOrder);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		model.addAttribute("picPrefix", picPrefix);
		return "modules/bu/buInternalOrderView";
	
	}
	
	/**
	 * 修改数据保存
	 * @param request
	 * @param response
	 * @param buOrder
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:edit")
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		buOrder.setOrderState(BusinessConstant.ORDER_STATE_1001);
        User user = UserUtils.getUser();
        
        Office office = user.getOffice();
        buOrder.setOffice(office);
        String siteId = Site.getCurrentSiteId();
        Site site = new Site();
        site.setId(siteId);
        buOrder.setSite(site);
        
		BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
		buOrder.setSalesManName(salesMan.getSalesmanName());
        
        buOrder.setCreateBy(user);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        buOrder.setOrderDate(format.format(new Date()));
        buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
        buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		buOrderService.save(buOrder);
		
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
		
	}
	
	/**
	 * 修改数据保存
	 * @param request
	 * @param response
	 * @param buOrder
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:edit")
	@RequestMapping(value = "update")
	public String update(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
        User user = UserUtils.getUser();
        
        Office office = user.getOffice();
        buOrder.setOffice(office);
        String siteId = Site.getCurrentSiteId();
        Site site = new Site();
        site.setId(siteId);
        buOrder.setSite(site);
        
		BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
		buOrder.setSalesManName(salesMan.getSalesmanName());
        
        buOrder.setCreateBy(user);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        buOrder.setOrderDate(format.format(new Date()));
        buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
        buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		buOrderService.save(buOrder);
		
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
		
	}

	@RequiresPermissions("bu:buInternalOrder:operate:update")
	@RequestMapping(value = "updateDelivery")
	public String updateDelivery(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {

		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		String id = request.getParameter("id");
		User user = UserUtils.getUser();

		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		
		if(buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1000)){
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1001);
		}else if(buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1001)){
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1002);
		}else if(buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1002)){
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1003);
		}else if(buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1003)){
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1004);
		}else if(buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1004)){
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1005);
		}else if(buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1005)){
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1006);
		}
		
		buOrder.setId(id);
		buOrder.setUpdateBy(user);
		buOrder.setUpdateDate(new Date());
		buOrderService.updateDelivery(buOrder);
		
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
		
	}
	
	protected BuOrderCp constructBuOrderCpEntity(BuOrder buOrder) {

		BuOrderCp orderCp = new BuOrderCp();

		orderCp.setOrderNo(buOrder.getOrderNo());
		orderCp.setProductNo(buOrder.getProductNo());
		orderCp.setOrderDate(buOrder.getOrderDate());
		orderCp.setShipDate(buOrder.getShipDate());
		orderCp.setProductName(buOrder.getProductName());

		orderCp.setCrafts(buOrder.getCrafts());
		orderCp.setElectroplate(buOrder.getElectroplate());
		orderCp.setBack(buOrder.getBack());
		orderCp.setPackages(buOrder.getPackages());
		orderCp.setFitting(buOrder.getFitting());

		orderCp.setPicUrl(buOrder.getPicUrl());
		orderCp.setQuantity(buOrder.getQuantity());
		orderCp.setSalesPrice(buOrder.getSalesPrice());
		orderCp.setSalesModelFee(buOrder.getSalesModelFee());
		orderCp.setProduceFee(buOrder.getProduceFee());

		orderCp.setProduceModelFee(buOrder.getProduceModelFee());
		orderCp.setSalesTotalFee(buOrder.getSalesTotalFee());
		orderCp.setProduceTotalFee(buOrder.getProduceTotalFee());

		return orderCp;

	}

	@RequiresPermissions("bu:buInternalOrder:operate:delete")
	@RequestMapping(value = "delete")
	public String delete(BuOrder buOrder, RedirectAttributes redirectAttributes) {
		buOrderService.delete(buOrder);
		addMessage(redirectAttributes, "删除成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
	}

	@RequiresPermissions("bu:buInternalOrder:operate:copy")
	@RequestMapping(value = "copy")
	public String copy(HttpServletRequest request, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		
		User user = UserUtils.getUser();
		
		Role customerRole = new Role();
		User customerUser = new User();
		/**
		 * 业务员
		 */
		customerRole.setId(BusinessConstant.CUSTOMER_ROLE_ID);
		customerUser.setRole(customerRole);
		customerUser.setDelFlag(BusinessConstant.NOT_DEL_FLAG);

		User supplierUser = new User();
		Role supplierRole = new Role();
		/**
		 * 厂商
		 */
		supplierRole.setId(BusinessConstant.SUPPLIER_ROLE_ID_002);
		supplierRole.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		supplierUser.setRole(supplierRole);

		List<User> supplierList = userService.findRef(supplierUser);
		List<User> customerList = userService.findRef(customerUser);

		model.addAttribute("supplierList", supplierList);
		model.addAttribute("customerList", customerList);
		
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(user.getId());
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		model.addAttribute("entityList", entityList);
		
		model.addAttribute("buOrder", buOrder);
		buOrder.setOrderNo(DateUtil.getDate());
		model.addAttribute("flag", flag);
		model.addAttribute("picPrefix", picPrefix);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderCopy";
	}

	/**
	 * 追加数据保存
	 * @param request
	 * @param response
	 * @param buOrder
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:edit")
	@RequestMapping(value = "copySave")
	public String copySave(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		User user = UserUtils.getUser();

		Office office = user.getOffice();
		buOrder.setOffice(office);
		String siteId = Site.getCurrentSiteId();
		Site site = new Site();
		site.setId(siteId);
		buOrder.setSite(site);
		BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
		buOrder.setSalesManName(salesMan.getSalesmanName());
		
		buOrder.setCreateBy(user);
		buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		buOrder.setOrderState(BusinessConstant.ORDER_STATE_1001);
		buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		buOrder.setIsNewRecord(true);
		buOrder.setId(IdGen.uuid());
		buOrderService.save(buOrder);
		
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
		
	}
	
	/**
	 * 管理员数据保存
	 * 
	 * @param request
	 * @param response
	 * @param buOrder
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:edit")
	@RequestMapping(value = "manageSave")
	public String manageSave(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {

		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		User user = UserUtils.getUser();

		Office office = user.getOffice();
		buOrder.setOffice(office);
		String siteId = Site.getCurrentSiteId();
		Site site = new Site();
		site.setId(siteId);
		buOrder.setSite(site);

		String customerId = buOrder.getCustomerId();
		String supplierId = buOrder.getSupplierId();

		User customerUser = new User();
		customerUser.setId(customerId);
		customerUser.setDelFlag(BusinessConstant.NOT_DEL_FLAG);

		User supplierUser = new User();
		supplierUser.setId(supplierId);
		supplierUser.setDelFlag(BusinessConstant.NOT_DEL_FLAG);

		List<User> supplierList = userService.findRef(supplierUser);
		List<User> customerList = userService.findRef(customerUser);

		buOrder.setSupplierName(supplierList.get(0).getName());
		buOrder.setCustomerName(customerList.get(0).getName());

		BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
		buOrder.setSalesManName(salesMan.getSalesmanName());

		buOrder.setCreateBy(user);
		buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		buOrderService.save(buOrder);

		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";

	}
	
	@RequestMapping(value = "selectSalesList")
	@ResponseBody
	public Map<String, Object> selectSalesList(BuOrder order, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String customerId = request.getParameter("id");
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(customerId);
		List<BuSalesman> entityList = Lists.newArrayList();
		String negativeOne = "-1";
		if(StringUtils.isNotBlank(customerId) && !(negativeOne).equals(customerId)){
			entityList = buSalesmanService.findList(salesman);
		}
		Map<String, Object> map = new HashMap<>(1);
		map.put("salesmanId", entityList);
		return map;

	}
	
	/**
	 * 查询订单状态
	 * 
	 * @return
	 */
	@RequestMapping(value = "orderStatus")
	@ResponseBody
	public Map<String, Object> getOrderStatus(HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>(0);
		return map;
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios0")
	@RequestMapping(value = "ios0")
	public void ios0(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios1")
	@RequestMapping(value = "ios1")
	public void ios1(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios2")
	@RequestMapping(value = "ios2")
	public void ios2(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios3")
	@RequestMapping(value = "ios3")
	public void ios3(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios4")
	@RequestMapping(value = "ios4")
	public void ios4(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios5")
	@RequestMapping(value = "ios5")
	public void ios5(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios6")
	@RequestMapping(value = "ios6")
	public void ios6(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * 下载生产单
	 * @param buOrder
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:export")
    @RequestMapping(value = "exportProductFile", method=RequestMethod.GET)
    public String exportProductFile(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			
            ExcelTest.reportOrderMergeXls(BusinessConstant.INNER_ORDER_TYPE_INT,buOrder, "xx", "yy",response,picPrefix,winUserfilesBasedir,linuxUserfilesBasedir);
		} catch (Exception e) {
			addMessage(redirectAttributes, "下载生产单！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/bu/buInternalOrder/list?repage";
    }
	
	
	
	/**
	 * 导出订单数据
	 * @param buOrder
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:btnExport")
    @RequestMapping(value = "downloadProductFile", method=RequestMethod.POST)
    public String downloadProductFile(BuOrder buOrder, HttpServletRequest request,Model model, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		
		Page<BuOrder> page = null;
		try{
			if(StringUtils.isBlank(buOrder.getInnerSalVal())){
				buOrder.setSalesmanId("");
			}
			if(StringUtils.isBlank(buOrder.getInnerSupVal())){
				buOrder.setSupplierId("");
			}
			
			User user = UserUtils.getUser();
			List<String> roleList = user.getRoleIdList();
			String roleId = String.valueOf(roleList.get(0));
			buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
			buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
			
			if(org.apache.commons.lang3.StringUtils.isNotBlank(buOrder.getSalesmanId())){
				if(!buOrder.getSalesmanId().equals(BusinessConstant.SEL_ORDER_STATE_FLAG)){
					BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
					buOrder.setSalesManName(salesMan.getSalesmanName());
				}
			}
			InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
			if(roleId.equals(BusinessConstant.SUPPLIER_ROLE_ID_001) || roleId.equals(BusinessConstant.SUPPLIER_ROLE_ID_002)){
				returnWrapper = this.constructSupplier(user, buOrder);
			}else{
				returnWrapper = this.constructAdmin(buOrder, user);
			}
			if (StringUtils.isNoneBlank(buOrder.getOrderState())) {
				if (buOrder.getOrderState().equals(BusinessConstant.SEL_ORDER_STATE_FLAG)) {
					buOrder.setOrderState("");
				} else {
					buOrder.setOrderState(buOrder.getOrderState().split(",")[0]);
				}
			}
			String negativeOne = "-1";
			if(StringUtils.isBlank(buOrder.getOrderState()) || (negativeOne).equals(buOrder.getOrderState())){
				List<String> orderStateList = constructOrderState();
				buOrder.setOrderStateList(orderStateList);
			}
			if((BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSupplierId())){
				buOrder.setSupplierId("");
			}
			if((BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
				buOrder.setSalesmanId("");
			}
			page = buOrderService.findExportPage(new Page<BuOrder>(request, response), buOrder);
			Integer innerOrderState = -1;
			if(!org.apache.commons.lang3.StringUtils.isBlank(buOrder.getOrderState())){
				innerOrderState = Integer.parseInt(buOrder.getOrderState());
			}
		
			String innerSalVal = "-1";
			if(StringUtils.isNotBlank(buOrder.getSalesmanId())){
				innerSalVal = buOrder.getSalesmanId();
			}
			
			BuSalesman salesman = new BuSalesman();
			salesman.setCustomerId(user.getId());
			List<BuSalesman> entityList = buSalesmanService.findList(salesman);
			
			ModelWrapper wrapper = new ModelWrapper(page, returnWrapper,entityList,innerOrderState,innerSalVal);
			model = this.constructDownModel(model, wrapper);
    		ExportToExcelUtil.out(picPrefix, response, page.getList());
    		return null;
    		
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导出订单数据失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/bu/buInternalOrder/list?repage";
    }
	
	private Model constructDownModel(Model model,ModelWrapper wrapper){
		
		model.addAttribute("salesmanlist",wrapper.getEntityList());
		model.addAttribute("picPrefix", picPrefix);
		model.addAttribute("page", wrapper.getPage());
		model.addAttribute("entity",wrapper.getReturnWrapper().getTotalEntity());
		model.addAttribute("innerOrderState", wrapper.getInnerOrderState());
		model.addAttribute("innerSupVal",wrapper.getReturnWrapper().getInnerVal());
		
		model.addAttribute("innerCusVal",wrapper.getReturnWrapper().getInnerVal());
		model.addAttribute("innerSalVal",wrapper.getInnerSalVal());
		model.addAttribute("supplierList",wrapper.getReturnWrapper().getSupplierList());
		return model;
		
	}
	
	private InternalReturnWrapper constructAdmin(BuOrder buOrder,User user){
		
		InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
		String innerVal = "";
		List<User> supplierList = Lists.newArrayList();
		TotalEntity entity = new TotalEntity();
		
		BuOrder buCr = new BuOrder();
		String negativeOne = "-1";
		if(StringUtils.isNotBlank(buOrder.getSupplierId()) && !(negativeOne).equals(buOrder.getSupplierId())){
			String supplierId = buOrder.getSupplierId();
			User supplieSelrUser = new User();
			List<String> idList = new ArrayList<>();
			idList.add(supplierId);
			supplieSelrUser.setIdList(idList);
			supplieSelrUser.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
			List<User> supplierSelList = userService.findRef(supplieSelrUser);
			buOrder.setCreateUser(supplierSelList.get(0).getName());
			buCr.setCreateUser(supplierSelList.get(0).getName());
		}
		
		List<User> supSelList = Lists.newArrayList();
		List<String> supSelIdList = Lists.newArrayList();
		User supSelUser = new User();
		Role supSelRole = new Role();
		
		/**
		 * 厂商角色ID
		 */
		supSelRole.setId(BusinessConstant.SUPPLIER_ROLE_ID_001);
		supSelRole.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		supSelUser.setRole(supSelRole);
		
		if (StringUtils.isNotBlank(buOrder.getSupplierId()) && !(negativeOne).equals(buOrder.getSupplierId())) {
			supSelIdList.add(buOrder.getSupplierId());
			supSelUser.setIdList(supSelIdList);
			supSelList = userService.findRef(supSelUser);
			innerVal = supSelList.get(0).getId();
		}
		
		User supplierUser = new User();
		Role supplierRole = new Role();
		/**
		 * 厂商角色ID
		 */
		supplierRole.setId(BusinessConstant.SUPPLIER_ROLE_ID_001); 
		supplierRole.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		supplierUser.setRole(supplierRole);

		supplierList = userService.findRefRole(supplierUser);
		
		if(StringUtils.isNotBlank(buOrder.getSalesmanId()) && !(BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
			buCr.setSalesmanId(buOrder.getSalesmanId());
		}
		
		buCr.setCreateUser(user.getName());
		buCr.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		buCr.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		entity = buOrderService.findAllTotal(buCr);
		
		returnWrapper.setInnerVal(innerVal);
		returnWrapper.setTotalEntity(entity);
		returnWrapper.setSupplierList(supplierList);
		return returnWrapper;
		
	}
	
	private InternalReturnWrapper constructSupplier(User user,BuOrder buOrder){
		
			InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
			TotalEntity totalEntity = new TotalEntity();
			String innerVal = "";
			
			BuOrder buCr = new BuOrder();
			buCr.setCreateBy(user);
			
			if(StringUtils.isNotBlank(buOrder.getSalesmanId()) && !(BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
				buCr.setSalesmanId(buOrder.getSalesmanId());
			}
			
			buCr.setCreateUser(user.getName());
			buCr.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
			buCr.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
			totalEntity = buOrderService.findCreateById(buCr);
			buCr.setCreateUser(UserUtils.getUser().getName());
			innerVal = UserUtils.getUser().getId();
			buOrder.setCreateUser(user.getName());
			
			returnWrapper.setBuInternalOrder(buOrder);
			returnWrapper.setInnerVal(innerVal);
			returnWrapper.setTotalEntity(totalEntity);
			
			return returnWrapper;
	}
	
	/**
	 * 批量收款
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:batchReceipt")
	@RequestMapping(value = "batchReceipt")
	public String batchReceipt(HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes){
		String ids = request.getParameter("ids");
		String[] idsArr = ids.split(",");
		List<String> idList = new ArrayList<>();
		for(int i = 0;i<idsArr.length;i++){
			idList.add(idsArr[i]);
		}
		BuOrder buOrder = new BuOrder();
		buOrder.setOrderState(BusinessConstant.ORDER_STATE_1006);
		User user = UserUtils.getUser();
		buOrder.setUpdateBy(user);
		buOrder.setUpdateDate(new Date());
		buOrder.setIdList(idList);
		buOrderService.updateBatchReceipt(buOrder);
		return "redirect:" + adminPath + "/bu/buInternalOrder/list?repage";
	}
	
	/**
	 * 管理员角色用户客户查询条件权限
	 * @param request
	 * @param buOrder
	 * @param model
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:manageSales")
	@RequestMapping(value = "sales")
	public void searchForSales(HttpServletRequest request,BuOrder buOrder,Model model){
		
	}
	
	/**
	 * 管理员角色用户厂商查询条件权限
	 * @param request
	 * @param buOrder
	 * @param model
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:manageSupplier")
	@RequestMapping(value = "supplier")
	public void searchForSupplier(HttpServletRequest request,BuOrder buOrder,Model model){
		
	}
	
	/**
	 * 厂商角色用户客户查询条件权限
	 * @param request
	 * @param buOrder
	 * @param model
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:supplierSales")
	@RequestMapping(value = "supplierSales")
	public void supplierSales(HttpServletRequest request,BuOrder buOrder,Model model){
		
	}
	
	public BuOrder constructBuOrder(HttpServletRequest request) throws ParseException{
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		BuOrder buOrder = new BuOrder();
		String supValStr = request.getParameter("supVal") == null ? "" : request.getParameter("supVal");
		String cusValStr = request.getParameter("cusVal") == null ? "" : request.getParameter("cusVal");
		String orderNoStr = request.getParameter("orderNo") == null ? "" : request.getParameter("orderNo");
		String productNoStr = request.getParameter("productNo") == null ? "" : request.getParameter("productNo");
		
		String beginOrderDateStr = request.getParameter("beginOrderDate") == null ? "" : request.getParameter("beginOrderDate");
		String endOrderDateStr = request.getParameter("endOrderDate") == null ? "" : request.getParameter("endOrderDate");
		String beginShipDateStr = request.getParameter("beginShipDate") == null ? "" : request.getParameter("beginShipDate");
		String endShipDateStr = request.getParameter("endShipDate") == null ? "" : request.getParameter("endShipDate");
		
		String productNameStr = request.getParameter("productName") == null ? "" : request.getParameter("productName");
		String orderStateStr = request.getParameter("orderState") == null ? "" : request.getParameter("orderState");
		
		String customerIdStr = request.getParameter("customerId") == null ? "" : request.getParameter("customerId");
		String salesmanIdStr = request.getParameter("salesmanId") == null ? "" : request.getParameter("salesmanId");
		String supplierIdStr = request.getParameter("supplierId") == null ? "" : request.getParameter("supplierId");
		String pageNoStr = request.getParameter("pageNo") == null ? "" : request.getParameter("pageNo");
		String pageSizeStr = request.getParameter("pageSize") == null ? "" : request.getParameter("pageSize");

		buOrder.setCusVal(cusValStr);
		buOrder.setSupVal(supValStr);
		
		buOrder.setOrderNo(orderNoStr);
		buOrder.setProductNo(productNoStr);
		if(StringUtils.isNotEmpty(beginOrderDateStr)){
			buOrder.setBeginOrderDate(format.parse(beginOrderDateStr));
		}
		if(StringUtils.isNotEmpty(endOrderDateStr)){
			buOrder.setEndOrderDate(format.parse(endOrderDateStr));
		}
		if(StringUtils.isNotEmpty(beginShipDateStr)){
			buOrder.setBeginShipDate(format.parse(beginShipDateStr));
		}
		if(StringUtils.isNotEmpty(endShipDateStr)){
			buOrder.setEndShipDate(format.parse(endShipDateStr));
		}
		if(orderStateStr.equals(BusinessConstant.SEL_ORDER_STATE_FLAG)){
			buOrder.setOrderDate("");
		}else{
			buOrder.setOrderState(orderStateStr);
		}
		if(salesmanIdStr.equals(BusinessConstant.SEL_ORDER_STATE_FLAG)){
			buOrder.setSalesmanId("");
		}else{
			buOrder.setSalesmanId(salesmanIdStr);
		}
		
		buOrder.setProductName(productNameStr);
		buOrder.setCustomerId(customerIdStr);
		buOrder.setSupplierId(supplierIdStr);
		
		Page<BuOrder> page = new Page<>();
		if(StringUtils.isNotEmpty(pageNoStr)){
			page.setPageNo(Integer.parseInt(String.valueOf(pageNoStr)));
		}
		if(StringUtils.isNotEmpty(pageSizeStr)){
			page.setPageSize(Integer.parseInt(String.valueOf(pageSizeStr)));
		}
		buOrder.setPage(page);
		
		return buOrder;
	}
	
	/**
	 * 批量收款
	 * 
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:batchReceipt")
	@RequestMapping(value = "ajaxBatchReceipt")
	@ResponseBody
	public String ajaxBatchReceipt(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json = new JSONObject();
		String ids = request.getParameter("ids");
		String[] idsArr = ids.split(",");
		List<String> idList = new ArrayList<>();
		for (int i = 0; i < idsArr.length; i++) {
			idList.add(idsArr[i]);
		}
		BuOrder buOrder = new BuOrder();
		buOrder.setOrderState(BusinessConstant.ORDER_STATE_1006);
		User user = UserUtils.getUser();
		buOrder.setUpdateBy(user);
		buOrder.setUpdateDate(new Date());
		buOrder.setIdList(idList);
		buOrderService.updateBatchReceipt(buOrder);
		json.put("msg", "批量收款成功");
		json.put("code", 222);
		return json.toString();
	}
	
	@RequiresPermissions("bu:buInternalOrder:operate:update")
	@RequestMapping(value = "ajaxUpdateDelivery")
	@ResponseBody
	public String ajaxUpdateDelivery(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		String id = request.getParameter("id");
		User user = UserUtils.getUser();

		buOrder = buOrderService.findById(buOrder);
		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		if (buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1000)) {
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1001);
		} else if (buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1001)) {
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1002);
		} else if (buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1002)) {
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1003);
		} else if (buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1003)) {
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1004);
		} else if (buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1004)) {
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1005);
		} else if (buOrder.getOrderState().equals(BusinessConstant.ORDER_STATE_1005)) {
			buOrder.setOrderState(BusinessConstant.ORDER_STATE_1006);
		}
		buOrder.setId(id);
		buOrder.setUpdateBy(user);
		buOrder.setUpdateDate(new Date());
		buOrderService.updateDelivery(buOrder);

		JSONObject json = new JSONObject();
		json.put("flag", flag);
		json.put("write", write);
		json.put("msg", "保存成功");
		json.put("code", 222);
		return json.toString();

	}
	
	private InternalReturnWrapper constructJsonOfSupplierDataEntity(User user,BuOrder buOrder,HttpServletRequest request,HttpServletResponse response){
		
		InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
		
		String innerVal = "-1";
		TotalEntity entity = new TotalEntity();
		Page<BuOrder> page = null;
		
		BuOrder buCr = new BuOrder();
		buCr.setCreateBy(user);
		innerVal = user.getId();
		if(StringUtils.isNotBlank(buOrder.getSalesmanId()) && !(BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
			buCr.setSalesmanId(buOrder.getSalesmanId());
		}
		buCr.setCreateUser(user.getName());
		buCr.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		buCr.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		
		buCr.setSalesmanId(buOrder.getSalesmanId());
		buCr.setOrderState(buOrder.getOrderState());
		buCr.setBeginShipDate(buOrder.getBeginShipDate());
		buCr.setEndShipDate(buOrder.getEndShipDate());
		buCr.setProductNo(buOrder.getProductNo());

		buCr.setBeginOrderDate(buOrder.getBeginOrderDate());
		buCr.setEndOrderDate(buOrder.getEndOrderDate());
		buCr.setProductName(buOrder.getProductName());
		
		entity = buOrderService.findCreateById(buCr);
		buOrder.setCreateBy(user);
		page = buOrderService.findInnerCreateByPage(new Page<BuOrder>(request, response), buOrder);
		
		returnWrapper.setPage(page);
		returnWrapper.setTotalEntity(entity);
		returnWrapper.setInnerVal(innerVal);
		
		return returnWrapper;
	}
	
	private InternalReturnWrapper constructJsonOfAtherData(BuOrder buOrder,User user){
		
		InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
		
		String innerVal = "-1";
		List<User> supplierList = Lists.newArrayList();
		TotalEntity entity = new TotalEntity();
		
		String negativeOne = "-1";
		if(StringUtils.isNotBlank(buOrder.getSupplierId()) && !(negativeOne).equals(buOrder.getSupplierId())){
			String supplierId = buOrder.getSupplierId();
			User supplieSelrUser = new User();
			List<String> idList = new ArrayList<>();
			idList.add(supplierId);
			supplieSelrUser.setIdList(idList);
			supplieSelrUser.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
			List<User> supplierSelList = userService.findRef(supplieSelrUser);
			buOrder.setCreateUser(supplierSelList.get(0).getName());
		}
		
		List<User> supSelList = Lists.newArrayList();
		List<String> supSelIdList = Lists.newArrayList();
		User supSelUser = new User();
		Role supSelRole = new Role();
		
		/**
		 * 厂商角色ID
		 */
		supSelRole.setId(BusinessConstant.SUPPLIER_ROLE_ID_001);
		supSelRole.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		supSelUser.setRole(supSelRole);
		if (StringUtils.isNotBlank(buOrder.getSupplierId()) && !(negativeOne).equals(buOrder.getSupplierId())) {
				supSelIdList.add(buOrder.getSupplierId());
				supSelUser.setIdList(supSelIdList);
				supSelList = userService.findRef(supSelUser);
				innerVal = supSelList.get(0).getId();
			}
		
		User supplierUser = new User();
		Role supplierRole = new Role();
		/**
		 * 厂商角色ID
		 */
		supplierRole.setId(BusinessConstant.SUPPLIER_ROLE_ID_001);
		supplierRole.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		supplierUser.setRole(supplierRole);

		supplierList = userService.findRefRole(supplierUser);
		BuOrder buCr = new BuOrder();
		if(StringUtils.isNotBlank(buOrder.getSalesmanId()) && !(BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
			buCr.setSalesmanId(buOrder.getSalesmanId());
		}
		buCr.setCreateBy(user);
		buCr.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
		buCr.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
		
		buCr.setSalesmanId(buOrder.getSalesmanId());
		buCr.setOrderState(buOrder.getOrderState());
		buCr.setBeginShipDate(buOrder.getBeginShipDate());
		buCr.setEndShipDate(buOrder.getEndShipDate());
		buCr.setProductNo(buOrder.getProductNo());

		buCr.setBeginOrderDate(buOrder.getBeginOrderDate());
		buCr.setEndOrderDate(buOrder.getEndOrderDate());
		buCr.setProductName(buOrder.getProductName());
		
		entity = buOrderService.findAllTotal(buCr);
		
		returnWrapper.setInnerVal(innerVal);
		returnWrapper.setSupplierList(supplierList);
		returnWrapper.setTotalEntity(entity);
		return returnWrapper;
		
	}
	
	/**
	 * flag (0:审核;1:修改;2:查看;3:新增;4:复制)
	 * @param buOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = "json")
	@ResponseBody
	public Map<String, Object> json(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, Model model) {

		Page<BuOrder> page = null;
		TotalEntity entity = new TotalEntity();
		JSONObject json = new JSONObject();
		try{
			buOrder = constructBuOrder(request);
			
			User user = UserUtils.getUser();
			List<String> roleList = user.getRoleIdList();
			String roleId = String.valueOf(roleList.get(0));
			buOrder.setOrderType(BusinessConstant.INNER_ORDER_TYPE);
			buOrder.setDelFlag(BusinessConstant.NOT_DEL_FLAG);
			
			InternalReturnWrapper returnWrapper = new InternalReturnWrapper();
			if(roleId.equals(BusinessConstant.SUPPLIER_ROLE_ID_001) || roleId.equals(BusinessConstant.SUPPLIER_ROLE_ID_002)){
				returnWrapper = this.constructJsonOfSupplierDataEntity(user, buOrder, request, response);
			}else{
				returnWrapper = this.constructJsonOfAtherData(buOrder, user);
			}
			if (StringUtils.isNoneBlank(buOrder.getOrderState())) {
				if (buOrder.getOrderState().equals(BusinessConstant.SEL_ORDER_STATE_FLAG)) {
					buOrder.setOrderState("");
				} else {
					buOrder.setOrderState(buOrder.getOrderState().split(",")[0]);
				}
			}
			String negativeOne = "-1";
			if(StringUtils.isBlank(buOrder.getOrderState()) || (negativeOne).equals(buOrder.getOrderState())){
				List<String> orderStateList = constructOrderState();
				buOrder.setOrderStateList(orderStateList);
			}
			if((BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSupplierId())){
				buOrder.setSupplierId("");
			}
			if((BusinessConstant.SEL_ORDER_STATE_FLAG).equals(buOrder.getSalesmanId())){
				buOrder.setSalesmanId("");
			}
			page = buOrderService.findPage(new Page<BuOrder>(request, response), buOrder);
			Integer innerOrderState = -1;
			if(!org.apache.commons.lang3.StringUtils.isBlank(buOrder.getOrderState())){
				innerOrderState = Integer.parseInt(buOrder.getOrderState());
			}
		
			String innerSalVal = "-1";
			if(StringUtils.isNotBlank(buOrder.getSalesmanId())){
				innerSalVal = buOrder.getSalesmanId();
			}
			json.put("picPrefix", picPrefix);
			json.put("page", page);
			json.put("entity", entity);
			json.put("innerOrderState", innerOrderState);
			model.addAttribute("innerSupVal", returnWrapper.getInnerVal());
			json.put("resultCode", 222);
			json.put("innerCusVal", returnWrapper.getInnerVal());
			json.put("innerSalVal", innerSalVal);
			json.put("supplierList", returnWrapper.getSupplierList());
		}catch(Exception e){
			e.printStackTrace();
			json.put("resultCode", 555);
		}
		return json;
	}
	
}
